#!/bin/bash

# httpclient4cj 测试运行脚本
# Copyright (c) 2025 httpclient4cj Contributors. All rights reserved.

set -e

echo "🚀 httpclient4cj 测试套件"
echo "=========================="

# 检查环境
echo "📋 检查环境..."
if ! command -v cjpm &> /dev/null; then
    echo "❌ 错误: 未找到 cjpm 命令"
    echo "请确保已安装仓颉语言开发环境"
    exit 1
fi

echo "✅ 仓颉环境检查通过"

# 设置环境变量
export DEEPSEEK_API_KEY="${DEEPSEEK_API_KEY:-sk-e86d943b677d47599abe6b89e98097b4}"
echo "🔑 使用API密钥: ${DEEPSEEK_API_KEY:0:10}..."

# 构建项目
echo ""
echo "🔨 构建项目..."
if ! cjpm build; then
    echo "❌ 项目构建失败"
    exit 1
fi
echo "✅ 项目构建成功"

# 运行测试
echo ""
echo "🧪 开始运行测试..."

# 测试计数器
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 运行基础HTTP测试
echo ""
echo "1️⃣ 运行基础HTTP测试..."
TOTAL_TESTS=$((TOTAL_TESTS + 1))
if cjpm run httpclient4cj.tests.basic_http_test; then
    echo "✅ 基础HTTP测试通过"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo "❌ 基础HTTP测试失败"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

# 运行DeepSeek API测试
echo ""
echo "2️⃣ 运行DeepSeek API测试..."
TOTAL_TESTS=$((TOTAL_TESTS + 1))
if cjpm run httpclient4cj.tests.deepseek_api_test; then
    echo "✅ DeepSeek API测试通过"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo "❌ DeepSeek API测试失败"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

# 运行综合测试
echo ""
echo "3️⃣ 运行综合测试..."
TOTAL_TESTS=$((TOTAL_TESTS + 1))
if cjpm run httpclient4cj.tests.comprehensive_test; then
    echo "✅ 综合测试通过"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo "❌ 综合测试失败"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

# 运行单元测试
echo ""
echo "4️⃣ 运行单元测试..."
TOTAL_TESTS=$((TOTAL_TESTS + 1))
if cjpm run httpclient4cj.tests.unit_test; then
    echo "✅ 单元测试通过"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo "❌ 单元测试失败"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

# 运行集成测试
echo ""
echo "5️⃣ 运行集成测试..."
TOTAL_TESTS=$((TOTAL_TESTS + 1))
if cjpm run httpclient4cj.tests.integration_test; then
    echo "✅ 集成测试通过"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo "❌ 集成测试失败"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

# 运行性能测试
echo ""
echo "6️⃣ 运行性能测试..."
TOTAL_TESTS=$((TOTAL_TESTS + 1))
if cjpm run httpclient4cj.tests.performance_test; then
    echo "✅ 性能测试通过"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo "❌ 性能测试失败"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

# 询问是否运行压力测试
echo ""
echo "7️⃣ 压力测试 (可选)"
echo "⚠️  注意: 压力测试可能需要较长时间"
read -p "是否运行压力测试? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    if cjpm run httpclient4cj.tests.stress_test; then
        echo "✅ 压力测试通过"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo "❌ 压力测试失败"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
else
    echo "跳过压力测试"
fi

# 测试结果汇总
echo ""
echo "📊 测试结果汇总"
echo "=========================="
echo "总测试数: ${TOTAL_TESTS}"
echo "通过测试: ${PASSED_TESTS}"
echo "失败测试: ${FAILED_TESTS}"

if [ $FAILED_TESTS -eq 0 ]; then
    echo ""
    echo "🎉 所有测试通过！"
    echo "httpclient4cj 库功能正常"
    exit 0
else
    echo ""
    echo "⚠️ 有 ${FAILED_TESTS} 个测试失败"
    echo "请检查网络连接和API配置"
    exit 1
fi
